<?php

declare(strict_types=1);

namespace App\Controller\v1;

use App\Controller\AbstractController;
use App\Exception\BusinessException;
use App\Service\UserProfilesService;
use App\Service\UserService;
use Hyperf\Context\Context;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\PutMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;

#[Controller(prefix: "/api/v1/users")]
class UserController extends AbstractController
{
    #[Inject]
    private UserService $userService;

    #[Inject]
    private UserProfilesService $userProfilesService;


    /**
     * 用户资料更新接口
     * @param RequestInterface $request
     * @return array|ResponseInterface
     */
    #[PutMapping("profile")]
    public function profile(RequestInterface $request): array|ResponseInterface
    {
        // 获取用户id
        $userId = Context::get("login_user_id") . "";

        // 解析参数
        $params = $this->parseParams($request);

        // 开启事务
        try {
            Db::beginTransaction();
            $this->userService->updateUser($params, $userId);
            $this->userProfilesService->updateUserProfiles($params, $userId);
            Db::commit();

        } catch (BusinessException $e) {
            Db::rollBack();
            return $this->fail(40002, "请求失败", ["errors" => $e->getMessage()]);
        }

        // 格式化用户信息
        $ret = $this->getFullUserData($userId);

        return $this->success($ret, "更新成功");
    }

    /**
     *  返回统一包含格式的用户信息
     * @param string $userId
     * @return array
     */
    private function getFullUserData(string $userId): array
    {
        $data = [];
        $userData = $this->userService->getUserById($userId);

        // 只取id name 和头像
        $data['id'] = $userData['id'];
        $data['name'] = $userData['name'];
        $data['avatar'] = $userData['avatar'];

        // 用户profile信息
        $profiles = $this->userProfilesService->getUserProfiles($userId);
        $data['profile'] = $profiles;
        return $data;
    }


}
